﻿using eLoan.Models;
using System;
using System.Web.Mvc;

namespace eLoan.Controllers
{
    public class LoanDeductionController : Controller
    {
        
        public ActionResult AddEdit(string documentNo, string command)
        {
            try
            {
                var db = new DatabaseContext();
                ViewBag.DocumentNo = documentNo;

                var loanDeductionsModel = FundingHelper.GetLoanDeductionAddEditModel(db, documentNo, command);
                return View("AddEditDeductions", loanDeductionsModel);

            }
            catch (Exception ex)
            {
                return View("Error", ex);
            }
        }

        [HttpPost]
        public ActionResult Save(LoanDeductionAddEditModel loanDeduction, string afterSave)
        {
            try
            {
                string documentNo = "0";
                var arr = afterSave.Split(',');
                documentNo = arr[1];

                if (ModelState.IsValid)
                {
                    using (var db = new DatabaseContext())
                    {
                        if (arr[0] == AdministrationHelper.DBCommand.Add.ToString())
                        {
                            foreach (var item in loanDeduction.LoanDeductions)
                            {
                                db.LoanDeductions.Add(item.LoanDeduction);
                            }

                            db.SaveChanges();
                        }
                        else if (arr[0] == AdministrationHelper.DBCommand.Edit.ToString())
                        {
                            foreach (var item in loanDeduction.LoanDeductions)
                            {
                                db.Entry(item.LoanDeduction).State = System.Data.EntityState.Modified;
                            }
                            
                            db.SaveChanges();
                        }
                        else
                        {
                            // cancelled
                        }
                    }
                }

                return RedirectToAction("LoanDetails", "Loan", new { documentNo = documentNo });
            }
            catch (Exception ex)
            {
                return View("Error", ex);
            }

            
        }

    }
}
